package stack;

public class ArrayStack implements IStack {
	private int size;
	private int gf;
	private Object[] array;
	
	public ArrayStack() {
		super();
		this.size = 0;
		this.gf = 0;
		this.array = new Object[2];
	}
	
	public ArrayStack(int gf) {
		super();
		this.size = 0;
		this.gf = (gf < 0) ? (-1 * gf) : gf;
		this.array = new Object[2];
	}
	
	@Override
	public int size() {
		return size;
	}
	
	@Override
	public boolean isEmpty() {
		return size == 0;
	}
	
	@Override
	public Object top() throws EmptyStackException {
		if (isEmpty()) {
			throw new EmptyStackException(null);
		}
		return array[size];
	}
	
	@Override
	public void push(Object o) {
		if(size >= array.length) {
			Object[] temp;
			if(gf == 0) {
				temp = new Object[array.length * array.length];
			} else {
				temp = new Object[size * gf];
			}
			for(int i = 0; i < size; i++) {
				temp[i] = array[i];
			}
			array = temp;
		}
		array[size++] = o;
	}
	
	@Override
	public Object pop() throws EmptyStackException {
		if (isEmpty()) {
			throw new EmptyStackException(null);
		}
		Object o = array[size];
		array[size--] = null;
		return o;
	}

	@Override
	public String toString() {
		String out = "ArrayStack:\n";
		for(int i = 0; i < array.length; i++) {
			out += "\t" +
					((array[i] != null) ?
							array[i].toString() : "vazio") +
					"\n";
		}
		return out;
	}
	
	public String elementsToString() {
		String out = "ArrayStack:\n";
		if(!isEmpty()) {
			for(int i = 0; i < size; i++) {
				out += "\t" +
						((array[i] != null) ?
								array[i].toString() : "vazio") +
						"\n";
			}
		} else {
			out = "ArrayStack: vazio\n";
		}
		return out;
	}
}
